package com.homedo.async.mysql.support.mapper.util;

import com.homedo.plainly.logger.Logger;
import com.homedo.plainly.logger.LoggerFactory;
import io.vertx.sqlclient.*;
import reactor.core.publisher.Mono;
import reactor.core.publisher.MonoSink;

import java.util.List;
import java.util.stream.Collector;

/**
 * @author jgshun
 * @date 2020/3/17 12:08 PM
 */
public abstract class CreateMono4RecordResultUtil {
    private static final Logger _LOGGER = LoggerFactory.getLogger(CreateMono4RecordResultUtil.class);

    public static <T> Mono<T> create(Object[] prepareSqlArgs, Pool pool, Collector<Row, ?, List<T>> collector, SqlConnection connection) {

        return Mono.create(sink -> {
            if (connection == null) {
                pool.getConnection(connRes -> {
                    if (connRes.succeeded()) {
                        SqlConnection newConnection = connRes.result();
                        create(prepareSqlArgs, collector, newConnection, true, sink);
                    } else {
                        sink.error(connRes.cause());
                    }
                });
            } else {
                create(prepareSqlArgs, collector, connection, false, sink);
            }
        });

    }

    private static <T> void create(Object[] prepareSqlArgs, Collector<Row, ?, List<T>> collector, SqlConnection connection, boolean close, MonoSink<T> sink) {
        connection.preparedQuery(prepareSqlArgs[0].toString(), Tuple.tuple((List<Object>) prepareSqlArgs[1]), collector, res -> {
            if (res.succeeded()) {
                SqlResult<List<T>> result = res.result();
                if (result.size() > 0) {
                    sink.success(result.value().get(0));
                } else {
                    sink.success();
                }
            } else {
                sink.error(res.cause());
                _LOGGER.error("Failure: {}", res.cause().getMessage(), res.cause());
            }

            if (close) {
                connection.close();
            }
        });

    }


}
